import React, { useState, useCallback } from 'react';
import { useEditor, EditorContent } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Image from '@tiptap/extension-image';
import Link from '@tiptap/extension-link';
import TextAlign from '@tiptap/extension-text-align';
import Underline from '@tiptap/extension-underline';
import Strike from '@tiptap/extension-strike';
import { Button, Upload, Input, Modal, message, Space, Divider } from 'antd';
import { 
  BoldOutlined, 
  ItalicOutlined, 
  UnderlineOutlined, 
  StrikethroughOutlined,
  OrderedListOutlined,
  UnorderedListOutlined,
  PictureOutlined,
  VideoCameraOutlined,
  LinkOutlined,
  AlignLeftOutlined,
  AlignCenterOutlined,
  AlignRightOutlined,
  UndoOutlined,
  RedoOutlined
} from '@ant-design/icons';
import './RichTextEditor.scss';

const RichTextEditor = ({ content, onChange, placeholder = "开始写作..." }) => {
  const [isLinkModalVisible, setIsLinkModalVisible] = useState(false);
  const [isVideoModalVisible, setIsVideoModalVisible] = useState(false);
  const [linkUrl, setLinkUrl] = useState('');
  const [linkText, setLinkText] = useState('');
  const [videoUrl, setVideoUrl] = useState('');

  const editor = useEditor({
    extensions: [
      StarterKit,
      Image.configure({
        HTMLAttributes: {
          class: 'editor-image',
        },
      }),
      Link.configure({
        openOnClick: false,
        HTMLAttributes: {
          class: 'editor-link',
        },
      }),
      TextAlign.configure({
        types: ['heading', 'paragraph'],
      }),
      Underline,
      Strike,
    ],
    content: content || '',
    onUpdate: ({ editor }) => {
      const html = editor.getHTML();
      const json = editor.getJSON();
      onChange && onChange({ html, json });
    },
  });

  // 图片上传处理
  const handleImageUpload = useCallback((file) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const url = e.target.result;
      editor?.chain().focus().setImage({ src: url }).run();
    };
    reader.readAsDataURL(file);
    return false; // 阻止默认上传行为
  }, [editor]);

  // 插入链接
  const insertLink = useCallback(() => {
    if (linkUrl && linkText) {
      editor?.chain().focus().insertContent(`<a href="${linkUrl}">${linkText}</a>`).run();
      setLinkUrl('');
      setLinkText('');
      setIsLinkModalVisible(false);
    }
  }, [editor, linkUrl, linkText]);

  // 插入视频
  const insertVideo = useCallback(() => {
    if (videoUrl) {
      let embedHtml = '';
      
      // YouTube视频处理
      if (videoUrl.includes('youtube.com') || videoUrl.includes('youtu.be')) {
        const videoId = videoUrl.includes('youtu.be') 
          ? videoUrl.split('/').pop().split('?')[0]
          : videoUrl.split('v=')[1]?.split('&')[0];
        
        if (videoId) {
          embedHtml = `<div class="video-wrapper" data-video-type="youtube">
            <iframe 
              src="https://www.youtube.com/embed/${videoId}?rel=0&modestbranding=1" 
              frameborder="0" 
              allowfullscreen
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
              width="100%" 
              height="315"
              title="YouTube视频">
            </iframe>
          </div>`;
        }
      }
      // Bilibili视频处理
      else if (videoUrl.includes('bilibili.com')) {
        let bvid = '';
        const bvMatch = videoUrl.match(/BV[a-zA-Z0-9]+/);
        const avMatch = videoUrl.match(/av(\d+)/);
        
        if (bvMatch) {
          bvid = bvMatch[0];
        } else if (avMatch) {
          bvid = `av${avMatch[1]}`;
        }
        
        if (bvid) {
          embedHtml = `<div class="video-wrapper" data-video-type="bilibili">
            <iframe 
              src="//player.bilibili.com/player.html?bvid=${bvid}&page=1&high_quality=1" 
              frameborder="0" 
              allowfullscreen
              width="100%" 
              height="315"
              title="Bilibili视频">
            </iframe>
          </div>`;
        }
      }
      // 腾讯视频处理
      else if (videoUrl.includes('v.qq.com')) {
        const vidMatch = videoUrl.match(/\/([a-zA-Z0-9]+)\.html/);
        if (vidMatch) {
          const vid = vidMatch[1];
          embedHtml = `<div class="video-wrapper" data-video-type="tencent">
            <iframe 
              src="https://v.qq.com/txp/iframe/player.html?vid=${vid}" 
              frameborder="0" 
              allowfullscreen
              width="100%" 
              height="315"
              title="腾讯视频">
            </iframe>
          </div>`;
        }
      }
      // 优酷视频处理
      else if (videoUrl.includes('youku.com')) {
        const idMatch = videoUrl.match(/id_([a-zA-Z0-9]+)/);
        if (idMatch) {
          const id = idMatch[1];
          embedHtml = `<div class="video-wrapper" data-video-type="youku">
            <iframe 
              src="https://player.youku.com/embed/${id}" 
              frameborder="0" 
              allowfullscreen
              width="100%" 
              height="315"
              title="优酷视频">
            </iframe>
          </div>`;
        }
      }
      // 直接视频链接
      else if (videoUrl.match(/\.(mp4|webm|ogg|avi|mov)$/i)) {
        embedHtml = `<div class="video-wrapper" data-video-type="direct">
          <video controls width="100%" height="315" preload="metadata">
            <source src="${videoUrl}" type="video/mp4">
            <source src="${videoUrl}" type="video/webm">
            <source src="${videoUrl}" type="video/ogg">
            您的浏览器不支持视频播放。
          </video>
        </div>`;
      }
      // 其他视频链接
      else {
        embedHtml = `<div class="video-wrapper" data-video-type="other">
          <iframe 
            src="${videoUrl}" 
            frameborder="0" 
            allowfullscreen
            width="100%" 
            height="315"
            title="视频播放器">
          </iframe>
        </div>`;
      }

      if (embedHtml) {
        editor?.chain().focus().insertContent(embedHtml).run();
        setVideoUrl('');
        setIsVideoModalVisible(false);
        message.success('视频插入成功');
      } else {
        message.error('无效的视频链接');
      }
    }
  }, [editor, videoUrl]);

  if (!editor) {
    return null;
  }

  return (
    <div className="rich-text-editor">
      {/* 工具栏 */}
      <div className="editor-toolbar">
        <Space wrap>
          {/* 文本格式 */}
          <Button
            size="small"
            type={editor.isActive('bold') ? 'primary' : 'default'}
            icon={<BoldOutlined />}
            onClick={() => editor.chain().focus().toggleBold().run()}
          />
          <Button
            size="small"
            type={editor.isActive('italic') ? 'primary' : 'default'}
            icon={<ItalicOutlined />}
            onClick={() => editor.chain().focus().toggleItalic().run()}
          />
          <Button
            size="small"
            type={editor.isActive('underline') ? 'primary' : 'default'}
            icon={<UnderlineOutlined />}
            onClick={() => editor.chain().focus().toggleUnderline().run()}
          />
          <Button
            size="small"
            type={editor.isActive('strike') ? 'primary' : 'default'}
            icon={<StrikethroughOutlined />}
            onClick={() => editor.chain().focus().toggleStrike().run()}
          />

          <Divider type="vertical" />

          {/* 列表 */}
          <Button
            size="small"
            type={editor.isActive('bulletList') ? 'primary' : 'default'}
            icon={<UnorderedListOutlined />}
            onClick={() => editor.chain().focus().toggleBulletList().run()}
          />
          <Button
            size="small"
            type={editor.isActive('orderedList') ? 'primary' : 'default'}
            icon={<OrderedListOutlined />}
            onClick={() => editor.chain().focus().toggleOrderedList().run()}
          />

          <Divider type="vertical" />

          {/* 对齐 */}
          <Button
            size="small"
            type={editor.isActive({ textAlign: 'left' }) ? 'primary' : 'default'}
            icon={<AlignLeftOutlined />}
            onClick={() => editor.chain().focus().setTextAlign('left').run()}
          />
          <Button
            size="small"
            type={editor.isActive({ textAlign: 'center' }) ? 'primary' : 'default'}
            icon={<AlignCenterOutlined />}
            onClick={() => editor.chain().focus().setTextAlign('center').run()}
          />
          <Button
            size="small"
            type={editor.isActive({ textAlign: 'right' }) ? 'primary' : 'default'}
            icon={<AlignRightOutlined />}
            onClick={() => editor.chain().focus().setTextAlign('right').run()}
          />

          <Divider type="vertical" />

          {/* 媒体插入 */}
          <Upload
            accept="image/*"
            beforeUpload={handleImageUpload}
            showUploadList={false}
          >
            <Button size="small" icon={<PictureOutlined />}>
              图片
            </Button>
          </Upload>

          <Button
            size="small"
            icon={<VideoCameraOutlined />}
            onClick={() => setIsVideoModalVisible(true)}
          >
            视频
          </Button>

          <Button
            size="small"
            icon={<LinkOutlined />}
            onClick={() => setIsLinkModalVisible(true)}
          >
            链接
          </Button>

          <Divider type="vertical" />

          {/* 撤销重做 */}
          <Button
            size="small"
            icon={<UndoOutlined />}
            onClick={() => editor.chain().focus().undo().run()}
            disabled={!editor.can().undo()}
          />
          <Button
            size="small"
            icon={<RedoOutlined />}
            onClick={() => editor.chain().focus().redo().run()}
            disabled={!editor.can().redo()}
          />
        </Space>
      </div>

      {/* 编辑器内容区 */}
      <div className="editor-content">
        <EditorContent editor={editor} placeholder={placeholder} />
      </div>

      {/* 插入链接模态框 */}
      <Modal
        title="插入链接"
        open={isLinkModalVisible}
        onOk={insertLink}
        onCancel={() => setIsLinkModalVisible(false)}
        okText="插入"
        cancelText="取消"
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          <Input
            placeholder="链接文本"
            value={linkText}
            onChange={(e) => setLinkText(e.target.value)}
          />
          <Input
            placeholder="链接地址"
            value={linkUrl}
            onChange={(e) => setLinkUrl(e.target.value)}
          />
        </Space>
      </Modal>

      {/* 插入视频模态框 */}
      <Modal
        title="插入视频"
        open={isVideoModalVisible}
        onOk={insertVideo}
        onCancel={() => setIsVideoModalVisible(false)}
        okText="插入"
        cancelText="取消"
        width={600}
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          <Input
            placeholder="请输入视频链接"
            value={videoUrl}
            onChange={(e) => setVideoUrl(e.target.value)}
            size="large"
          />
          
          <div className="video-help">
            <h4>支持的视频平台：</h4>
            <ul>
              <li><strong>YouTube:</strong> https://www.youtube.com/watch?v=VIDEO_ID</li>
              <li><strong>Bilibili:</strong> https://www.bilibili.com/video/BV1234567890</li>
              <li><strong>腾讯视频:</strong> https://v.qq.com/x/page/VIDEO_ID.html</li>
              <li><strong>优酷:</strong> https://v.youku.com/v_show/id_VIDEO_ID.html</li>
              <li><strong>直接链接:</strong> https://example.com/video.mp4</li>
            </ul>
            
            <div style={{ marginTop: 16, padding: 12, background: '#f6f8fa', borderRadius: 6 }}>
              <strong>提示：</strong>
              <ul style={{ margin: '8px 0 0 0', paddingLeft: 20 }}>
                <li>粘贴完整的视频页面链接即可</li>
                <li>支持大部分主流视频平台</li>
                <li>直接视频文件链接需要是公开可访问的</li>
              </ul>
            </div>
          </div>
        </Space>
      </Modal>
    </div>
  );
};

export default RichTextEditor;